// 封装购物车模块

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from '@/store/user'
import { insertCartAPI, fineNewCartListAPI, delCartAPI } from '@/apis/cart.js'


export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  // 1. 定义state - cartList
  const cartList = ref([])
  // 2. 定义action - addCart
  const addCart = async (goods) => {
    if (isLogin.value) {
      await insertCartAPI({
        skuId: goods.skuId,
        count: goods.count
      })
      updateCartList()
    } else {
      // 添加购物车操作
      // 已添加过 - count + 1
      // 没有添加过 - 直接push
      // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        // 找到了
        item.count = goods.count
      } else {
        // 没找到
        cartList.value.push(goods)
      }
    }

  }

  const delCart = async (skuId) => {
    // 删除购物车操作
    // 通过skuId找到对应的商品对象，然后删除
    if (isLogin.value) {
      // 登录状态下，调用接口删除
      await delCartAPI([skuId])
      const res = await fineNewCartListAPI();
      cartList.value = res.result || []
    } else {
      const index = cartList.value.findIndex((item) => item.skuId === skuId)
      if (index !== -1) {
        cartList.value.splice(index, 1)
      }
    }
  }

  const singleChange = (id, selected) => {
    // 单个选中或取消选中
    const item = cartList.value.find((item) => item.skuId === id)
    if (item) {
      item.selected = selected
    }
  }


  const changeEvent = (value) => {
    cartList.value.forEach(item => {
      item.selected = value
    })
  }

  const sum = computed(() => {
    return cartList.value.reduce((total, item) => {
      return total + item.count * item.price
    }, 0)
  })

  const checkAll = computed(() => {
    return cartList.value.every((item) => item.selected)
  })

  const clearCartList = () => {
    cartList.value = []
  }
  const updateCartList = async () => {
    const res = await fineNewCartListAPI();
    cartList.value = res.result || []
  }

  return {
    cartList,
    addCart,
    sum,
    delCart,
    singleChange,
    checkAll,
    changeEvent,
    clearCartList,
    updateCartList
  }
}, {
  persist: true,
})